package com.cxs.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/*
 * @Project:file-upload-senior
 * @Author:cxs
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@Component
public class FileUploadUtil {

    @Value("${file.upload-path}")
    private String filePath;

    /**
     * 校验文件的md5值
     * @param in
     * @param md5
     * @return
     */
    public Boolean checkMd5(InputStream in, String md5){
        if (null == in || null == md5) {
            return Boolean.FALSE;
        }
        try {
            if (DigestUtils.md5DigestAsHex(in).equalsIgnoreCase(md5)) {
                return Boolean.TRUE;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Boolean.FALSE;
    }


    /**
     * 生成文件路径
     * @return
     */
    public String getFilePath(){
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate now = LocalDate.now();
        String format = formatter.format(now);
        String datePath = filePath + File.separator + format;
        File fullFile = new File(datePath);
        if (!fullFile.exists()) {
            fullFile.mkdir();
        }
        return datePath;
    }
}
